﻿using LitJson;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace KjsyModUpdaterForWindows
{
    class DataAnalysis
    {
        public bool Analysis(MemoryStream stream)
        {
            if (stream.ReadByte() == Encoding.UTF8.GetBytes("{")[0])
                return AnalysisJson(stream);
            else
                return AnalysisList(stream);
        }

        private bool AnalysisJson(MemoryStream stream)
        {
            try
            {
                JsonData jd = JsonMapper.ToObject(Encoding.UTF8.GetString(stream.ToArray()));

                List<ModInfo> list = new List<ModInfo>();
                foreach(JsonData jdata in jd["base"])
                {
                    ModInfo mi = Tools.GetModInfo(jdata);
                    if (mi != null) list.Add(mi);
                }
                Program.baseModList = new BaseModList { Mod = list };

                list.Clear();

                foreach (JsonData jdata in jd["opinion"])
                {
                    ModInfo mi = Tools.GetModInfo(jdata);
                    if (mi != null) list.Add(mi);
                }
                Program.optionalModList = new OptionalModList { Mod = list };
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return false;
            }
            return true;
        }

        private bool AnalysisList(MemoryStream stream)
        {
            List<ModInfo> baselist = new List<ModInfo>();
            List<ModInfo> optilist = new List<ModInfo>();

            foreach (string i in Encoding.UTF8.GetString(stream.ToArray()).Split('\n'))
            {
                if (i.Split(';')[2] == "0") baselist.Add(Tools.GetModInfo(i));
                else optilist.Add(Tools.GetModInfo(i));
            }

            Program.baseModList = new BaseModList { Mod = baselist };
            Program.optionalModList = new OptionalModList { Mod = optilist };

            return true;
        }
    }
}
